<?php

class RedisService extends BaseService
{
    private static $self = NULL;
    private static $client = NULL;

    static public function instance()
    {
        if (self::$self == NULL) {
            self::$self = new self;
        }

        return self::$self;
    }




    private function __construct()
    {
        if (self::$client == NULL) {
            $this->getConnection();
        }

        return self::$client;
    }

    /**
     * 连接Redis
     * @return Redis
     */
    public function getConnection()
    {
        $redis = new Redis();
        $redisConf = Config::get("redis");
        list($host, $port) = explode(':', $redisConf['host']);
        $redis->connect($host, $port);
        return self::$client = $redis;;
    }

    /**复制redis
     * @return stdClass
     */
    public function getConnectionReplicate()
    {
        return new stdClass();
    }

    /**
     * 设置Key-Val
     * @param $key
     * @param $value
     * @param int $timeToCache
     */
    public function set($key, $value, $timeToCache = 0)
    {
        if (isset(self::$client->socket)) {
            self::$client->set($key, serialize($value), $timeToCache);
        } else {
            $redisReplicate = $this->getConnectionReplicate();
            $redisReplicate->set($key, serialize($value), $timeToCache);
        }
    }

    /**
     * 取值
     * @param $key
     * @return bool|string
     */
    public function get($key)
    {
        $res = self::$client->get($key);
        return unserialize($res);
    }

    public function getKeys()
    {
        return self::$client->keys();
    }

    /**
     * 是否存在
     * @param $key
     * @return mixed
     */
    public function exists($key)
    {
        return self::$client->exists($key);
    }

}